import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from email.mime.text import MIMEText

smtp_server = 'smtp.126.com'
smtp_port = 465
smtp_username = 'YCDZUKHVRAPTUOD3@126.com'
smtp_password = 'YCDZUKHVRAPTUOD'

def doSendEmail(recipient, title = '无主题', content = '无内容', filePath = ''):

    if isinstance(recipient, list):
        pass
    else:
        recipient = [recipient]
    # 创建一个MIMEMultipart对象作为邮件容器
    msg = MIMEText(content)
    # 附加Word文档
    if filePath.strip():
        msg = MIMEMultipart()
        msg.attach(MIMEText(content, 'html', 'utf-8'))
        attachment = open(filePath, 'rb')
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(attachment.read())
        encoders.encode_base64(part)
        file_name = os.path.basename(filePath)
        part.add_header('Content-Disposition', f'attachment; filename="{file_name}"')
        msg.attach(part)

    msg['From'] = smtp_username
    msg['To'] = ','.join(recipient)
    msg['Subject'] = title

    try:
        s = smtplib.SMTP_SSL("smtp.126.com", 465)  # 邮件服务器及端口号
        s.login(smtp_username, smtp_password)
        s.sendmail(smtp_username,  msg['To'].split(','), msg.as_string())
        print("发送成功")
    except:
        print("发送失败")